<template>
  <div>
    <el-card class="search-card">
      <BasicForm
        ref="formData"
        :colNumOfRow="4"
        formItemWidth="120px"
        :formColumns="formItemList"
        :dataSource="formData"
        :handleSearchForm="handleQueryForm"
        @getFormData="getFormData"
      />
    </el-card>
    <el-card class="table-card">
      <BasicTable
        :defaultMinWidth="100"
        showPagination
        isCustomSort
        :showSelectCol="true"
        :dataSource="tableInfo.list"
        :columns="tableInfo.columns"
        :loading="tableInfo.loading"
        :tableHeight="480"
        :selection-change="selectionChange"
        :pageSizes="pageSizes"
        :pagination="pagination"
        :total="total"
        @pageChange="handlePageChange"
        @pageSizeSelect="handlePageSizeChange"
        @customSortChange="handleSortTable"
      >
        <el-row type="flex" slot="content_context" justify="space-between">
          <div>
            <el-select class="type-select" size="mini" v-model="selectType" @change="handleTypeChange" placeholder="异常类型">
              <el-option
                v-for="item in ABNORMAL_TYPE_OPTIONS"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <el-button
              v-for="(item, index) in renderBtns()"
              size="mini"
              type="primary"
              :key="index"
              :loading="item.loading"
              :disabled="item.disabled"
              @click="item.method"
            >{{ item.btnTxet }}</el-button>
          </div>
          <div>
            <el-button size="mini" @click="showFieldSettingDialog">字段显示设置</el-button>
          </div>
        </el-row>
      </BasicTable>
    </el-card>
    <!-- 退回 -->
    <SendBackDialog :sendBackVisible.sync="sendBackVisible" :selectIds="selectIds" @getTableData="getTableData" />
    <!-- 审核 -->
    <AuditDialog :auditVisible.sync="auditVisible" :selectIds="selectIds" @getTableData="getTableData" />
    <!-- 提交 -->
    <SubmitDialog ref="submitDialog" :submitVisible.sync="submitVisible" :purchaseId="selectIds[0]" @getTableData="getTableData" />
    <!-- 追踪 -->
    <TrackDialog :trackVisible.sync="trackVisible" :isSameTrack="isSameTrack" :selectIds="selectIds" @getTableData="getTableData" />
    <!-- 说明 -->
    <DescDialog :descVisible.sync="descVisible" />
    <!-- 字段显示设置 -->
    <FieldSettingDialog
      :fieldSettingVisible.sync="fieldSettingVisible"
      :menuId="menuId"
      :selectType="abnormalType"
      @handleSetTableColumn="handleSetTableColumn"
    />
  </div>
</template>
<script>
import BasicForm from '@/components/BasicForm';
import BasicTable from '@/pages/purchase/components/BasicTable';
import SendBackDialog from './components/SendBackDialog';
import AuditDialog from './components/AuditDialog';
import SubmitDialog from './components/SubmitDialog';
import TrackDialog from './components/TrackDialog';
import DescDialog from './components/DescDialog';
import FieldSettingDialog from '@/pages/purchase/components/FieldSettingDialog';
import skusPage from '@/mixins/commodity/skusPage';
import { setAuthBtnId, createExcelByExport } from '@/utils/bizUtils';
import {
  queryAbnormalPurchaseListService,
  exportAbnormalPurchaseFileService,
  tempSaveAbnormalPurchaseService,
  queryTrackingDataIsSameService,
  queryTableFieldService,
  inverseTrackService
} from '@api/purchase/abnormalPurchase';
import {
  FORM_ITEMS,
  FORM_DATA,
  ABNORMAL_TYPE_OPTIONS,
} from './constants';

export default {
  mixins: [skusPage],
  components: {
    BasicForm,
    BasicTable,
    SendBackDialog,
    AuditDialog,
    SubmitDialog,
    TrackDialog,
    DescDialog,
    FieldSettingDialog
  },
  data () {
    return {
      selectType: 1, // 异常类型
      ABNORMAL_TYPE_OPTIONS,
      formItemList: FORM_ITEMS,
      formData: FORM_DATA,
      sortInfo: {},
      pageSizes: [10, 100, 1000],
      stashLoading: false,
      trackLoading: false,
      sendBackVisible: false,
      auditVisible: false,
      submitVisible: false,
      trackVisible: false,
      inverseTraceLoading: false,
      isSameTrack: false,
      descVisible: false,
      fieldSettingVisible: false,
    }
  },
  computed: {
    notSelected () {
      return this.tableInfo.selection.length === 0
    },
    selectIds () {
      return this.tableInfo.selection.map(item => item.abnormalPurchaseId)
    },
    menuId () {
      return sessionStorage.getItem('menuId')
    },
    abnormalType () {
      return this.selectType
    }
  },
  mounted () {
    this.handleTypeChange()
  },
  methods: {
    renderBtns () {
      const btns = [
        { btnTxet: '导出', loading: this.exportLoading, disabled: this.total == 0, method: this.handleExportFile, hasAuth: true },
        { btnTxet: '暂存待办', loading: this.stashLoading, disabled: this.notSelected, method: this.handleStash, hasAuth: true },
        { btnTxet: '退回', disabled: this.notSelected, method: this.handleSendBack, hasAuth: true },
        { btnTxet: '提交', loading: this.submitLoading, disabled: this.notSelected, method: this.handleSubmit, hasAuth: true },
        { btnTxet: '审核', disabled: this.notSelected, method: this.handleAudit, hasAuth: true },
        { btnTxet: '追踪', loading: this.trackLoading, disabled: this.notSelected, method: this.handleTrace, hasAuth: true },
        { btnTxet: '反追踪', loading: this.inverseTraceLoading, disabled: this.notSelected, method: this.handleInverseTrace, hasAuth: true },
        { btnTxet: '说明', method: this.viewInfo },
      ]
      return btns.filter(item => !item.hasAuth || (item.hasAuth && this.showBtn(item.btnTxet)));
    },
    // 勾选需要处理的库存
    selectionChange (rows) {
      this.tableInfo.selection = rows;
    },
    // 异常类型变更
    handleTypeChange () {
      this.pagination = {
        pageNum: 1,
        pageSize: 10
      }
      this.queryTableColumnField()
      this.getTableData()
    },
    // 查询表格表头
    async queryTableColumnField () {
      const { menuId, selectType } = this;
      const res = await queryTableFieldService({ menuId, selectType })
      if (res) {
        this.handleSetTableColumn(res.data)
      }
    },
    // 设置表头
    handleSetTableColumn (data) {
      const arr = data.filter(i => i.isShow).map(i => {
        return {
          sortable: !!i.isOrd,
          label: i.label,
          prop: i.prop,
          width: i.width,
        }
      })
      this.tableInfo.columns = arr;
    },
    // 表格排序
    handleSortTable (data) {
      const { prop, order } = data
      this.sortInfo = {
        orderby: prop,
        orderbyType: order
      }
      this.getTableData()
    },
    // 获取表单查询入参
    getSearchFormParams () {
      return {
        ...this.formData,
        ...this.sortInfo,
        selectType: this.selectType
      }
    },
    // 获取表格数据
    async getTableData () {
      setAuthBtnId();
      const res = await queryAbnormalPurchaseListService(
        { ...this.getSearchFormParams(), ...this.pagination },
        state => { this.tableInfo.loading = state }
      );
      if (res?.data) {
        const { list, total } = res.data;
        this.tableInfo.list = list;
        this.total = total;
      }
    },
    // 导出信息数据
    async handleExportFile () {
      const res = await exportAbnormalPurchaseFileService(
        { ...this.getSearchFormParams() },
        state => { this.exportLoading = state; }
      );
      createExcelByExport({ res, excelTitle: '异常采购' });
    },
    // 暂存待办
    async handleStash () {
      const params = {
        idList: this.selectIds
      }
      const res = await tempSaveAbnormalPurchaseService(params, state => { this.stashLoading = state })
      if (res) {
        this.$message.success('暂存成功')
        this.getTableData()
      }
    },
    // 退回
    handleSendBack () {
      this.sendBackVisible = true;
    },
    // 提交
    // 处理状态 10:待处理,20:暂存,30:退回,40:待审核,50:驳回，60:待审批,70:已处理"
    handleSubmit () {
      if (this.selectIds.length > 1) {
        return this.$message.warning('每次只能提交一条单据');
      }
      if (![30, 50].includes(this.tableInfo.selection[0].disposeStatus)) {
        return this.$message.warning('请选择退回或驳回状态单据提交');
      }
      this.$refs['submitDialog'].getTableData()
    },
    // 审核 40:待审核
    handleAudit () {
      if (this.tableInfo.selection.some(item => item.disposeStatus != 40)) {
        return this.$message.warning('请选择待审核状态单据执行此操作');
      }
      this.auditVisible = true;
    },
    // 追踪
    handleTrace () {
      // 追踪操作：非待处理，非暂存，非待审批不允许操作
      if (this.tableInfo.selection.some(item => ![10, 20, 60].includes(item.disposeStatus))) {
        return this.$message.warning('请选择待处理、暂存、待审批状态单据执行此操作');
      }
      this.queryTrackingDataIsSame()
    },
    // 反追踪
    async handleInverseTrace () {
      if (this.tableInfo.selection.some(item => item.disposeStatus != 70)) {
        return this.$message.warning('请选择已处理状态单据执行此操作');
      }
      const res = await inverseTrackService(
        { idList: this.selectIds },
        state => { this.inverseTraceLoading = state }
      )
      if (res) {
        this.$message.success(res.message)
        this.getTableData()
      }
    },
    // 判断追踪数据是否一致
    async queryTrackingDataIsSame () {
      const res = await queryTrackingDataIsSameService({ idList: this.selectIds }, state => { this.trackLoading = state })
      if (res) {
        if (res.data) {
          this.$confirm(`${res.data}`, '提示', {
            confirmButtonText: '继续',
            cancelButtonText: '关闭',
            type: 'warning'
          }).then(() => {
            this.trackVisible = true;
            this.isSameTrack = false;
          }).catch(() => {});
        } else {
          this.trackVisible = true;
          this.isSameTrack = true;
        }
      }
    },
    // 说明
    viewInfo () {
      this.descVisible = true;
    },
    // 字段显示设置
    showFieldSettingDialog () {
      this.fieldSettingVisible = true
    }
  }
}
</script>
<style scoped>
.type-select {
  width: 100px;
  margin-right: 10px;
}
</style>
